<?php
/*-------------------------------------------------------------------------\
|
|  ========================================================
|  Fusion Registry GPL
|  Copyright (C) 2007 Fusion Scripts
|
|  This program is free software; you can redistribute it and/or
|  modify it under the terms of the GNU General Public License
|  as published by the Free Software Foundation; either version 2
|  of the License, or (at your option) any later version.
|
|  This program is distributed in the hope that it will be useful,
|  but WITHOUT ANY WARRANTY; without even the implied warranty of
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
|  GNU General Public License for more details.
|
|  You should have received a copy of the GNU General Public License
|  along with this program; if not, write to the Free Software
|  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
|  ========================================================
|
|  Email: info@fusionscripts.com
|  Web-Site: http://www.fusionscripts.com/
|
|  $Id: index.php 15 2008-08-03 18:09:51Z registry.fusion $
|
\-------------------------------------------------------------------------*/

/**
 * Installation Program for Fusion Registry
 *
 * @package Fusion Registry
 * @subpackage installer
 * @version $Id: index.php 15 2008-08-03 18:09:51Z registry.fusion $
 */

// Setup
error_reporting(E_ERROR | E_WARNING | E_PARSE);
set_magic_quotes_runtime(0);

define( 'INS_ROOT_PATH', '../../../../../' );
define( 'INS_KERNEL_PATH', INS_ROOT_PATH.'ips_kernel/' );

define( 'FR_VERSION_SHORT', 'v3.0.5' );
define( 'FR_VERSION_LONG', '30005' );

require './template.php';

if ( !file_exists(INS_ROOT_PATH.'sources/ipsclass.php') )
{
    $template = new template();
    $template->install_error("Unable to locate the file: /sources/ipsclass.php<br /><br />Please ensure your forum is properly installed and that you have uploaded all Fusion Registry files to the correct location.");
    exit();
}

$INFO = array();

# Initiate super-class
if ( file_exists( INS_ROOT_PATH.'init.php' ) )
{
    require_once( INS_ROOT_PATH.'init.php' );
}
require INS_ROOT_PATH.'sources/ipsclass.php';
$ipsclass = new ipsclass();
$ipsclass->vars = $INFO;
$ipsclass->template = new template();

$ipsclass->parse_incoming();
$ipsclass->initiate_ipsclass();

// Installer locked?
if ( file_exists( './install.lock') )
{
    $ipsclass->template->install_error("This installer is locked!<br />Please (via FTP) remove the file 'install.lock' from this directory");
    exit();
}

// What step are we on?
switch($ipsclass->input['s'])
{
    case '1':
        do_checks();
        break;

    case '2':
        do_sql('tables');
        break;

    case '3':
        do_sql('inserts');
        break;

    // This step is optional!
    case '4':
        do_sql('makes_models');
        break;

    case '5':
        do_finish();
        break;

    default:
        do_intro();
        break;
}


/**
 * Welcome screen, no checking yet
 */
function do_intro()
{
    global $ipsclass;

    $ipsclass->template->print_header();

    $ipsclass->template->contents .= <<<HTML
Welcome to the Fusion Registry installer!<br />
<br />
Before you continue you must have your forum software installed and configured.<br />
<br />
This installer will guide you through the installation process starting off with a few pre-installation checks. When you are ready to proceed, click continue!<br />
<br />
<div align='center' style='color: red'><b>PLEASE NOTE: USING THIS INSTALLER WILL DELETE ANY CURRENT FUSION REGISTRY TABLES !!</b></div><br />
<br />
<div align='center'><a href="index.php?s=1" class='button' style='color: #003366'>Continue >></a></div>
HTML;

    $ipsclass->template->output();
}


/**
 * All our pre-installation checks
 */
function do_checks()
{
    global $ipsclass;

    $ipsclass->template->print_header( array( 'current_step' => 'Pre-Installation Checks' ) );

    // Brief explanation
    $ipsclass->template->contents .= "Below are the results of the pre-installation checks. Any check that results ".
                                     "in a 'NOTICE' means that you will be able to continue with the installation, but ".
                                     "there is important information you need to be aware of. Failures will prevent ".
                                     "the installation from continuing until you resolve the problem.<br /><br />";

    // Start results table
    $ipsclass->template->contents .= "<table cellspacing='4' cellpadding='4' border='0' width='100%'>".
                                     "<tr><td width='85%'><b>Verification Checks</b></td><td width='15%' style='font-weight: bold; text-align: center'>Result</td></tr>";

    $failures = 0;


    // Do we have a conf file?
    $conf_file = INS_ROOT_PATH.'conf_global.php';

    $check = 'Checking for conf_global.php';

    if ( ! file_exists( $conf_file ) )
    {
        $ipsclass->template->contents .= $ipsclass->template->check_fail( array( 'check' => $check, 'message' => "Cannot locate the conf_global.php file, this file should be located at the root directory of your forum directory." ) );
        $failures++;
    }
    else
    {
        $ipsclass->template->contents .= $ipsclass->template->check_pass( array( 'check' => $check, 'message' => 'Found it!' ) );

        // Import $INFO now
        require INS_ROOT_PATH.'conf_global.php';
    }

    // PHP version check
    $check = "Checking PHP version";

    $phpversion = phpversion();

    if ( version_compare( $phpversion, "4.3.0", ">=") )
    {
        $ipsclass->template->contents .= $ipsclass->template->check_pass( array( 'check' => $check, 'message' => "You are running PHP version $phpversion" ) );
    }
    else
    {
        // Should we fail this or just warn?
        if ( version_compare( $phpversion, "4.1.0", ">=") )
        {
            $ipsclass->template->contents .= $ipsclass->template->check_notice( array( 'check' => $check,
                                                'message' => "You are running PHP version $phpversion. PHP versions less than 4.3.0 do not support certain functions like 'html_entity_decode' and 'stream_set_timeout'. Any features requiring these functions will be ignored." ) );
        }
        else
        {
            // Should we fail this or just warn?
            $ipsclass->template->contents .= $ipsclass->template->check_fail( array( 'check' => $check,
                                                'message' => "You are running PHP version $phpversion. You cannot install Fusion Registry ". FR_VERSION_SHORT .". Fusion Registry requires PHP version 4.1.0 or better." ) );
            $failures++;
        }
    }


    // open_basedir check
    $open_basedir = @ini_get('open_basedir');

    $check = "Checking for open_basedir restrictions";

    if (empty($open_basedir) == FALSE)
    {
        $ipsclass->template->contents .= $ipsclass->template->check_notice( array( 'check' => $check,
                                            'message' => "Your PHP installation is configured with the <a href='http://www.php.net/manual/en/features.safe-mode.php#ini.open-basedir' target='_blank'>open_basedir</a> restriction. You will only be able to execute external commands for thumbnail generation in the following path(s): $open_basedir" ) );
    }
    else
    {
        $ipsclass->template->contents .= $ipsclass->template->check_pass( array( 'check' => $check, 'message' => 'None found!' ) );
    }


    // Safe Mode check
    $check = "Checking if safe_mode is enabled";

    if ( @ini_get("safe_mode") )
    {
        $ipsclass->template->contents .= $ipsclass->template->check_notice( array( 'check' => $check,
                                            'message' => "Your PHP installation is running with safe mode enabled, you will not be able to properly install the skin." ) );
    }
    else
    {
        $ipsclass->template->contents .= $ipsclass->template->check_pass( array( 'check' => $check, 'message' => 'It is not!' ) );
    }


    // allow_url_fopen check
    $check = "Checking if allow_url_fopen is enabled";

    if ( @ini_get("allow_url_fopen") )
    {
        $ipsclass->template->contents .= $ipsclass->template->check_pass( array( 'check' => $check, 'message' => 'It is!' ) );
    }
    else
    {
        $ipsclass->template->contents .= $ipsclass->template->check_notice( array( 'check' => $check,
                                            'message' => 'Your PHP installation is running with allow_url_fopen disabled, you will not be able to support remote image attachments.' ) );
    }


    // IPB version check
    $check = "Checking forum version";

    if ( file_exists( INS_ROOT_PATH.'init.php' ) )
    {
        if ( version_compare( empty( $ipsclass->acpversion ) ? $ipsclass->vn_full : $ipsclass->acpversion, "22009", ">=") )
        {
            $ipsclass->template->contents .= $ipsclass->template->check_pass( array( 'check' => $check,
                                                'message' => "You are running forum version $ipsclass->version" ) );
        }
        else
        {
            $ipsclass->template->contents .= $ipsclass->template->check_fail( array( 'check' => $check,
                                                'message' => "You are running forum version $ipsclass->version. You cannot install Fusion Registry ". FR_VERSION_SHORT .". Fusion Registry requires forum version 2.2.0 Final or better." ) );
            $failures++;
        }
    }
    else
    {
        $ipsclass->template->contents .= $ipsclass->template->check_fail( array( 'check' => $check,
                                            'message' => "You are running a forum version before version 2.2.0. You cannot install Fusion Registry ". FR_VERSION_SHORT .". Fusion Registry requires forum version 2.2.0 Final or better." ) );
        $failures++;
    }

    // Database check
    $check = "Checking database connection";

    require ( INS_KERNEL_PATH.'class_db_'.$INFO['sql_driver'].".php" );

    $classname = "db_driver_".$INFO['sql_driver'];

    $ipsclass->DB = new $classname;

    $ipsclass->DB->obj['sql_database']     = $INFO['sql_database'];
    $ipsclass->DB->obj['sql_user']         = $INFO['sql_user'];
    $ipsclass->DB->obj['sql_pass']         = $INFO['sql_pass'];
    $ipsclass->DB->obj['sql_host']         = $INFO['sql_host'];
    $ipsclass->DB->obj['sql_tbl_prefix']   = $INFO['sql_tbl_prefix'];
    $ipsclass->DB->obj['use_shutdown']     = 0;
    $ipsclass->DB->return_die              = 1;

    // Required vars?
    if ( is_array( $ipsclass->DB->connect_vars ) and count( $ipsclass->DB->connect_vars ) )
    {
        foreach( $ipsclass->DB->connect_vars as $k => $v )
        {
            $ipsclass->DB->connect_vars[ $k ] = $INFO[ $k ];
        }
    }

    // Attempt a connect
    if ( ! @$ipsclass->DB->connect() )
    {
        $ipsclass->template->contents .= $ipsclass->template->check_fail( array( 'check' => $check,
                                            'message' => $ipsclass->DB->error ) );
        $failures++;
    }
    else
    {
        $ipsclass->template->contents .= $ipsclass->template->check_pass( array( 'check' => $check,
                                            'message' => "Connection established!" ) );

        // Make CONSTANT
        define( 'SQL_PREFIX', $ipsclass->DB->obj['sql_tbl_prefix'] );
        define( 'SQL_DRIVER', strtolower($INFO['sql_driver']) );
    }


    // Finish results table
    $ipsclass->template->contents .= "</table><br /><br />";

    if ( $failures )
    {
        $ipsclass->template->contents .= "The failures above prevent you from continuing with the installation. If you can correct the failures return to this page and hit refresh to continue.";
    }
    else
    {
        $ipsclass->template->contents .= 'Congratulations, all verfication checks passed! The next step will install the sql tables, when you are ready to proceed click continue!<br /><br />'.
                                         '<div align="center" style="color: red"><b>PLEASE NOTE: CONTINUING TO THE NEXT STEP WILL DELETE ANY CURRENT FUSION REGISTRY TABLES !!<br /><br />THIS IS THE LAST WARNING !!</b></div><br /><br /><br />'.
                                         "<div align='center'><a href='index.php?s=2' class='button' style='color: #003366'>Continue >></a></div>";
    }

    $ipsclass->template->output();
}


function do_sql($type)
{
    global $ipsclass;

    // Do the heavy lifting
    $total_executed = execute_sql($type);

    if ( $type == 'tables' )
    {
        $current_step = 'Create SQL Tables';

        $next_step = "Successfully executed $total_executed SQL queries.<br /><br />".
                     "The next step will populate default information into the database. When you are ready to proceed click continue!<br /><br />".
                     "<div align='center'><a href='index.php?s=3' class='button' style='color: #003366'>Continue >></a></div>";
    }
    elseif ( $type == 'inserts' )
    {
        $current_step = 'Insert Default SQL Data';

        $next_step = "Successfully executed $total_executed SQL queries.<br /><br />".
                     "If you are running an automobile related site you may now optionally populate the Vehicle Makes and Models database with the entire default list.  If you choose not to do this step you will need to add all of your Vehicle Makes and Models manually through the ACP.<br /><br />".
                     "<div align='center'>Do you want to populate the Vehicle Makes and Models database? Please choose Yes or No to continue.</div><br />".
                     "<div align='center'><a href='index.php?s=5' class='button' style='color: #003366'>No >></a> &nbsp;&nbsp;&nbsp; <a href='index.php?s=4' class='button' style='color: #003366'>Yes >></a></div>";
    }
    elseif ( $type == 'makes_models' )
    {
        $current_step = 'Insert Vehicle Makes and Models';

        $next_step = "Successfully executed $total_executed SQL queries.<br /><br />".
                     "Click continue to finish up the installation<br /><br />".
                     "<div align='center'><a href='index.php?s=5' class='button' style='color: #003366'>Continue >></a></div>";
    }

    $ipsclass->template->print_header( array( 'current_step' => $current_step ) );

    // Brief explanation
    $ipsclass->template->contents .= $next_step;

    $ipsclass->template->output();
}


function execute_sql($type)
{
    global $ipsclass;

    // Import $INFO now
    require INS_ROOT_PATH.'conf_global.php';
    $ipsclass->vars = $INFO;

    require './sql_importer.php';

    $sql_importer = new sql_importer();
    $sql_importer->ipsclass =& $ipsclass;
    $sql_importer->auto_run();

    // Database connection
    require ( INS_KERNEL_PATH.'class_db_'.$INFO['sql_driver'].".php" );

    $classname = "db_driver_".$INFO['sql_driver'];

    $ipsclass->DB = new $classname;

    $ipsclass->DB->obj['sql_database']     = $INFO['sql_database'];
    $ipsclass->DB->obj['sql_user']         = $INFO['sql_user'];
    $ipsclass->DB->obj['sql_pass']         = $INFO['sql_pass'];
    $ipsclass->DB->obj['sql_host']         = $INFO['sql_host'];
    $ipsclass->DB->obj['sql_tbl_prefix']   = $INFO['sql_tbl_prefix'];
    $ipsclass->DB->obj['use_shutdown']     = 0;
    $ipsclass->DB->return_die              = 1;

    // Required vars?
    if ( is_array( $ipsclass->DB->connect_vars ) and count( $ipsclass->DB->connect_vars ) )
    {
        foreach( $ipsclass->DB->connect_vars as $k => $v )
        {
            $ipsclass->DB->connect_vars[ $k ] = $INFO[ $k ];
        }
    }

    // Attempt a connect
    if ( ! @$ipsclass->DB->connect() )
    {
        $ipsclass->template->install_error( "Connection error:<br /><br />".$ipsclass->DB->error );
    }

    // Go for it!
    $total_executed = $sql_importer->execute_sql_file('./sql/'.$type.'.sql.php');

    return $total_executed;
}


function do_finish()
{
    global $ipsclass;

    if ( $FH = @fopen( './install.lock', 'w' ) )
    {
        @fwrite( $FH, 'No Soup For You!', 16 );
        @fclose( $FH );

        @chmod( './install.lock', 0666 );

        $msg = "<b>The installation was successful!</b><br /><br />".
               "Although the installer is now locked, for added security, please remove the install directory before continuing:<br />'".getcwd()."'<br /><br /><br />".
               "<div align='center'><a href='".INS_ROOT_PATH."/admin.php?section=components&act=registry&menu=config' target='_blank' class='button' style='color: #003366'>Login to ACP to Configure >></a></div>";
    }
    else
    {
        $msg = "<b>The installation was successful!</b><br /><br />".
               "PLEASE REMOVE THE INSTALL DIRECTORY '".getcwd()."BEFORE CONTINUING!<br>Failure to do so will enable ANYONE to delete your Fusion Registry tables at any time!<br /><br /><br />".
               "<div align='center'><a href='".INS_ROOT_PATH."/admin.php?section=components&act=registry&menu=config' target='_blank' class='button' style='color: #003366'>Login to ACP to Configure >></a></div>";
    }

    $ipsclass->template->print_header( array( 'current_step' => 'Installation Finished!' ) );

    $ipsclass->template->contents .= $msg;

    $ipsclass->template->output();
}